<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片转Base64</title>
</head>
<body>
    <div id="box" style="width: 100px; height: 100px;"></div>
    <img src="" id="pic" />
    <canvas id="mycanvas"></canvas>

    <script>
        // function getUrlBase64(url,ext,callback){
        //     var canvas = document.createElement("canvas");
        //     var ctx = canvas.getContext("2d");
        //     var img = new Image;
        //     img.crossOrigin = "Anonymous";
        //     img.src = url;
        //     img.onload = function(){
        //         canvas.width = img.width;
        //         canvas.height = img.height;
        //         ctx.drawImage(img,0,0,img.height,img.width);
        //         var dataURL = canvas.toDataURL("images/" + ext);
        //         callback.call(this,dataURL);
        //         canvas = null;
        //     }
        // }    
        //将图片转成Base64
        var imgUrl = "./images/daguanxiaoxue_shenhua.jpg";
        var pic = document.getElementById("pic");
        var box = document.getElementById("box");
        
        function getUrlBase64(url) {
            var canvas = document.createElement("canvas");   //创建canvas DOM元素
            var ctx = canvas.getContext("2d");
            var extIndex = url.lastIndexOf(".");
            var ext = url.substr(extIndex + 1);
            if(ext == "jpg"){
                ext = "jpeg";
            }
            var img = new Image();
            img.crossOrigin = 'Anonymous';
            img.src = url;
            img.onload = function () {
                canvas.width = img.width; //指定画板的高度,自定义
                canvas.height = img.height; //指定画板的宽度，自定义
                ctx.drawImage(img, 0, 0, img.width, img.height); //参数可自定义
                var dataURL = canvas.toDataURL("image/" + ext);
                //callback.call(this, dataURL); //回掉函数获取Base64编码
                box.innerHTML = dataURL;
                canvas = null;
            };
            
            return img.onload();
        };
        console.log(getUrlBase64(imgUrl));

        
        // function setImage(url){
        //     var canvas = document.createElement("canvas");
        //     var ctx = canvas.getContext("2d");
        //     var imgObject = new Image();
        //     imgObject.crossOrigin = "Anonymous"
        //     imgObject.src = url;
        //     imgObject.onload = function(){
        //         canvas.width = imgObject.width;
        //         canvas.height = imgObject.height;
        //         ctx.drawImage(imgObject,0,0,imgObject.width,imgObject.height);
        //     }
        //     return canvas;
        // }
        // var iH = setImage(imgUrl);
        // box.appendChild(iH);
    </script>
</body>
</html>